package main

import (
	"errors"
	"flag"
	"fmt"
	"io/ioutil"
	"os"
)

var dirPath = flag.String("dir", "", "dir to encode/decode")

func main() {
	flag.Parse()

	if *dirPath == "" {
		panic("必须输入dir")
	}

	coder := NewCoder(*dirPath)

	lockfile := lockPath(*dirPath)

	var err error

	action, err := checkType(*dirPath)
	if err != nil {
		panic(err)
	}

	switch action {
	case "init":
		err = Init(coder, lockfile)
		if err != nil {
			panic(err)
		}
		fallthrough
	case "encode":
		err = Encode(coder, lockfile)
	case "decode":
		err = Decode(coder, lockfile)
	}

	if err != nil {
		panic(err)
	}

	fmt.Println("成功！")
}

func Init(coder *Coder, lockfile string) error {
	err := coder.Init()
	if err != nil {
		return err
	}
	open, err := os.Create(lockfile)
	if err != nil {
		return err
	}
	return open.Close()
}

func Encode(coder *Coder, lockfile string) error {
	err := coder.Encode()
	if err != nil {
		return err
	}
	open, err := os.Create(lockfile)
	if err != nil {
		return err
	}
	defer open.Close()
	_, err = open.WriteString("coded")
	err = open.Sync()
	return err
}

func Decode(coder *Coder, lockfile string) error {
	err := coder.Decode()
	if err != nil {
		return err
	}
	open, err := os.Create(lockfile)
	if err != nil {
		return err
	}
	return open.Close()
}

func lockPath(path string) string {
	return encodeString(path)
}

func checkType(path string) (string, error) {

	bytes, err := ioutil.ReadFile(lockPath(path))

	if err != nil {
		return "init", nil
	}

	if string(bytes) == "coded" {
		return "decode", nil
	}

	if string(bytes) == "" {
		return "encode", nil
	}

	return "", errors.New("错误的锁定文件" + path)
}
